Popular Searches
Popular Course Categories
Popular Courses

Detecting screen size and dimensions

Detecting screen size and dimensions

Flutter Responsive Design


Detecting Screen Size and Dimensions in Flutter


Detecting screen size and dimensions is an important part of building responsive and adaptive Flutter applications. Flutter applications can run on mobile phones, tablets, foldable devices, desktop windows, ChromeOS, and the web, so the available application space can change significantly.


Flutter provides APIs such as MediaQuery.sizeOf(), MediaQuery.widthOf(), MediaQuery.heightOf(), and LayoutBuilder to determine the space available to an application or a particular widget. Flutter recommends making layout decisions based on the available window size rather than simply identifying a device as a phone or tablet. :contentReference[oaicite:0]{index=0}


1. What Does Screen Size Mean in Flutter?


In Flutter, screen or window dimensions used for layout are normally expressed in logical pixels. Logical pixels are device-independent units that generally provide a similar visual size across devices with different physical pixel densities.


The current application window size can be accessed using:


final Size size = MediaQuery.sizeOf(context);

The Size object contains two important values:



  • size.width - available window width

  • size.height - available window height


Flutter's documentation recommends MediaQuery.sizeOf() rather than MediaQuery.of(context).size when the application only needs the size. :contentReference[oaicite:1]{index=1}


2. Why Detect Screen Size?


Screen-size detection is useful when an application needs to change its layout according to the available space.



  • Change a single-column layout into multiple columns.

  • Change bottom navigation into a navigation rail.

  • Resize cards and images.

  • Change padding and margins.

  • Display a sidebar on larger windows.

  • Limit content width on large screens.

  • Create responsive dashboards.

  • Change the number of grid columns.

  • Prevent horizontal overflow.

  • Create tablet and desktop-friendly layouts.


The important concept is that the layout should respond to the space actually available to the application, because the same physical device can run an application in a smaller window. :contentReference[oaicite:2]{index=2}


3. Using MediaQuery to Detect Screen Size


The most common approach is:


final size = MediaQuery.sizeOf(context);

You can then read the dimensions:


final width = size.width;
final height = size.height;

print("Width: $width");
print("Height: $height");


4. Detecting Screen Width


Use MediaQuery.widthOf(context) when you only need the current application-window width.


final double width = MediaQuery.widthOf(context);

print("Window Width: $width");


Example:


import 'package:flutter/material.dart';

class ScreenWidthExample extends StatelessWidget {
  const ScreenWidthExample({super.key});

  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.widthOf(context);

    return Scaffold(
      appBar: AppBar(
        title: const Text("Screen Width"),
      ),
      body: Center(
        child: Text(
          "Width: $width logical pixels",
          style: const TextStyle(fontSize: 20),
        ),
      ),
    );
  }
}


5. Detecting Screen Height


Use MediaQuery.heightOf(context) when you only need the current application-window height.


final double height = MediaQuery.heightOf(context);

print("Window Height: $height");


Example:


class ScreenHeightExample extends StatelessWidget {
  const ScreenHeightExample({super.key});

  @override
  Widget build(BuildContext context) {
    final height = MediaQuery.heightOf(context);

    return Scaffold(
      body: Center(
        child: Text(
          "Height: $height logical pixels",
          style: const TextStyle(fontSize: 20),
        ),
      ),
    );
  }
}


6. Detecting Both Width and Height


The MediaQuery.sizeOf() method is useful when both dimensions are required.


Widget build(BuildContext context) {
  final size = MediaQuery.sizeOf(context);

  final width = size.width;
  final height = size.height;

  return Column(
    mainAxisAlignment: MainAxisAlignment.center,
    children: [
      Text("Width: $width"),
      Text("Height: $height"),
    ],
  );
}


7. Complete Screen Dimension Example


import 'package:flutter/material.dart';

class ScreenDimensions extends StatelessWidget {
  const ScreenDimensions({super.key});

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.sizeOf(context);

    return Scaffold(
      appBar: AppBar(
        title: const Text("Screen Dimensions"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              "Width: ${size.width}",
              style: const TextStyle(fontSize: 22),
            ),
            const SizedBox(height: 10),
            Text(
              "Height: ${size.height}",
              style: const TextStyle(fontSize: 22),
            ),
          ],
        ),
      ),
    );
  }
}


8. Understanding Logical Pixels


Flutter layout dimensions are generally expressed in logical pixels rather than raw physical pixels.


For example:


Container(
  width: 200,
  height: 100,
)

The values 200 and 100 represent logical layout units. The physical number of pixels used by the device depends on its pixel density.


Flutter's MediaQueryData.size is measured in logical pixels, while physical display dimensions can be obtained through lower-level display APIs when the physical display itself is specifically required. :contentReference[oaicite:3]{index=3}


9. Screen Size vs Physical Display Size


It is important to understand the difference between the application's available window and the physical display.








ConceptMeaningTypical API
Application window sizeSpace currently available to the Flutter applicationMediaQuery.sizeOf(context)
Local widget constraintsSpace provided to a specific widget by its parentLayoutBuilder
Physical display sizeActual display dimensions reported by the underlying view/displayDisplay/FlutterView
Device pixel ratioRelationship between physical and logical pixelsMediaQuery.of(context).devicePixelRatio

For normal responsive UI decisions, application-window size is generally the appropriate value. Physical display dimensions are needed only for specific scenarios such as certain foldable or display-level requirements. :contentReference[oaicite:4]{index=4}


10. Using MediaQuery.of(context)


The traditional approach is:


final mediaQuery = MediaQuery.of(context);

final width = mediaQuery.size.width;
final height = mediaQuery.size.height;


This works, but if you only need the size, Flutter recommends the more specific MediaQuery.sizeOf() API because it creates a more targeted dependency and can avoid rebuilds caused by unrelated MediaQuery changes. :contentReference[oaicite:5]{index=5}


11. MediaQuery.sizeOf() vs MediaQuery.of()








MethodUsage
MediaQuery.of(context)Access the complete MediaQueryData
MediaQuery.sizeOf(context)Access only the current window size
MediaQuery.widthOf(context)Access only the current window width
MediaQuery.heightOf(context)Access only the current window height

When only one property is required, using the specific method is generally preferred. :contentReference[oaicite:6]{index=6}


12. Detecting Small, Medium, and Large Screens


After detecting the width, you can define breakpoints for different layouts.


Widget build(BuildContext context) {
  final width = MediaQuery.widthOf(context);

  if (width < 600) {
    return const Text("Small Screen");
  } else if (width < 1024) {
    return const Text("Medium Screen");
  } else {
    return const Text("Large Screen");
  }
}


These values are examples, not universal device classifications. Breakpoints should be selected according to the layout requirements. Flutter's adaptive guidance recommends basing UI changes on available window size rather than physical device categories. :contentReference[oaicite:7]{index=7}


13. Creating a Screen Size Helper


You can create a reusable helper class to avoid repeating the same calculations.


class ScreenSize {
  static double width(BuildContext context) {
    return MediaQuery.widthOf(context);
  }

  static double height(BuildContext context) {
    return MediaQuery.heightOf(context);
  }

  static bool isSmall(BuildContext context) {
    return width(context) < 600;
  }

  static bool isMedium(BuildContext context) {
    final value = width(context);
    return value >= 600 && value < 1024;
  }

  static bool isLarge(BuildContext context) {
    return width(context) >= 1024;
  }
}


Usage:


if (ScreenSize.isSmall(context)) {
  return const MobileLayout();
}

if (ScreenSize.isMedium(context)) {
  return const TabletLayout();
}

return const DesktopLayout();


14. Detecting Screen Orientation


You can obtain the current orientation using MediaQuery:


final orientation = MediaQuery.orientationOf(context);

if (orientation == Orientation.portrait) {
  print("Portrait");
} else {
  print("Landscape");
}


However, orientation should generally not be the main basis for selecting a complete application layout. A landscape phone and a narrow desktop window can have very different requirements despite similar orientation. Flutter recommends using available window size through MediaQuery.sizeOf() or local constraints through LayoutBuilder. :contentReference[oaicite:8]{index=8}


15. Responsive UI Based on Width


A common responsive pattern is to switch layouts based on width.


class ResponsivePage extends StatelessWidget {
  const ResponsivePage({super.key});

  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.widthOf(context);

    if (width < 600) {
      return const MobileView();
    }

    return const WideView();
  }
}


16. Responsive Row and Column


On a narrow window, content can be displayed vertically. On a wider window, the same content can be displayed horizontally.


Widget build(BuildContext context) {
  final width = MediaQuery.widthOf(context);

  if (width < 600) {
    return const Column(
      children: [
        ProfileCard(),
        ProfileDetails(),
      ],
    );
  }

  return const Row(
    children: [
      Expanded(
        child: ProfileCard(),
      ),
      Expanded(
        child: ProfileDetails(),
      ),
    ],
  );
}


17. Responsive Grid Based on Screen Width


Screen dimensions can be used to determine the number of grid columns.


Widget build(BuildContext context) {
  final width = MediaQuery.widthOf(context);

  int columns;

  if (width < 600) {
    columns = 2;
  } else if (width < 1000) {
    columns = 3;
  } else {
    columns = 4;
  }

  return GridView.builder(
    padding: const EdgeInsets.all(16),
    gridDelegate:
        SliverGridDelegateWithFixedCrossAxisCount(
      crossAxisCount: columns,
      crossAxisSpacing: 16,
      mainAxisSpacing: 16,
    ),
    itemCount: 20,
    itemBuilder: (context, index) {
      return Card(
        child: Center(
          child: Text("Item ${index + 1}"),
        ),
      );
    },
  );
}


For large-screen layouts, the number of columns should be determined by the available window size rather than whether the hardware is classified as a tablet or phone. :contentReference[oaicite:9]{index=9}


18. Responsive Card Width


You can calculate a card width using the available window width.


Widget build(BuildContext context) {
  final width = MediaQuery.widthOf(context);

  final cardWidth = width < 600
      ? width * 0.9
      : 400.0;

  return Center(
    child: SizedBox(
      width: cardWidth,
      child: const Card(
        child: Padding(
          padding: EdgeInsets.all(20),
          child: Text("Responsive Card"),
        ),
      ),
    ),
  );
}


19. Maximum Width on Large Screens


On a large display, making a text field or content area fill the entire width can reduce readability. A maximum width is often more appropriate.


Widget build(BuildContext context) {
  final width = MediaQuery.widthOf(context);

  final contentWidth =
      width > 800 ? 700.0 : width * 0.9;

  return Center(
    child: SizedBox(
      width: contentWidth,
      child: const Text(
        "This content has a maximum width on large screens.",
      ),
    ),
  );
}


Flutter's large-screen guidance specifically recommends considering maximum widths rather than simply filling all available horizontal space. :contentReference[oaicite:10]{index=10}


20. Responsive Navigation


Screen width can be used to change navigation patterns.


Widget build(BuildContext context) {
  final width = MediaQuery.widthOf(context);

  if (width < 600) {
    return const Scaffold(
      bottomNavigationBar: NavigationBar(
        destinations: [
          NavigationDestination(
            icon: Icon(Icons.home),
            label: "Home",
          ),
          NavigationDestination(
            icon: Icon(Icons.person),
            label: "Profile",
          ),
        ],
      ),
      body: Center(
        child: Text("Mobile Layout"),
      ),
    );
  }

  return const Scaffold(
    body: Row(
      children: [
        NavigationRail(
          selectedIndex: 0,
          destinations: [
            NavigationRailDestination(
              icon: Icon(Icons.home),
              label: Text("Home"),
            ),
            NavigationRailDestination(
              icon: Icon(Icons.person),
              label: Text("Profile"),
            ),
          ],
        ),
        Expanded(
          child: Center(
            child: Text("Large Layout"),
          ),
        ),
      ],
    ),
  );
}


A 600 logical-pixel threshold is commonly used in Flutter's adaptive examples for distinguishing compact from larger layouts, but applications should select breakpoints based on their own UI requirements. :contentReference[oaicite:11]{index=11}


21. Detecting Screen Height for Vertical Layouts


Width is usually the most important responsive dimension, but height can also be useful.


final height = MediaQuery.heightOf(context);

if (height < 600) {
  return const CompactVerticalLayout();
}

return const NormalVerticalLayout();


For example, you may reduce vertical spacing when the available window is short.


final height = MediaQuery.heightOf(context);

final spacing = height < 600 ? 8.0 : 24.0;

Column(
  children: [
    const Text("Welcome"),
    SizedBox(height: spacing),
    const Text("Login"),
  ],
)


22. Detecting Available Screen Space with LayoutBuilder


MediaQuery measures the application's window, while LayoutBuilder measures the constraints provided to a particular widget by its parent.


LayoutBuilder(
  builder: (context, constraints) {
    final width = constraints.maxWidth;
    final height = constraints.maxHeight;

    return Text(
      "Width: $width, Height: $height",
    );
  },
)


This is especially useful when a component needs to adapt to its own available area instead of the entire application window. :contentReference[oaicite:12]{index=12}


23. MediaQuery vs LayoutBuilder








MediaQueryLayoutBuilder
Measures application window sizeMeasures local parent constraints
Returns a SizeProvides BoxConstraints
Useful for app-level responsive decisionsUseful for component-level responsive decisions
Example: switch navigation structureExample: change a card layout based on its container

Flutter's adaptive documentation recommends choosing between these approaches according to whether you need the whole application-window size or a widget's local available space. :contentReference[oaicite:13]{index=13}


24. Detecting Safe Screen Dimensions


Screen content can be affected by status bars, notches, camera cutouts, rounded corners, and other system UI. MediaQuery provides padding information for these areas.


final padding = MediaQuery.paddingOf(context);

print("Top: ${padding.top}");
print("Bottom: ${padding.bottom}");
print("Left: ${padding.left}");
print("Right: ${padding.right}");


For ordinary content, SafeArea is usually easier and safer than manually applying these values.


Scaffold(
  body: SafeArea(
    child: YourContent(),
  ),
)

SafeArea uses MediaQuery information internally to protect content from system UI and display cutouts. :contentReference[oaicite:14]{index=14}


25. Detecting Keyboard-Reduced Space


When the software keyboard appears, part of the visible area can be obstructed. You can inspect this using viewInsets.


final bottomInset =
    MediaQuery.viewInsetsOf(context).bottom;

print("Keyboard height: $bottomInset");


This can be useful for custom keyboard-aware interfaces.


Padding(
  padding: EdgeInsets.only(
    bottom: MediaQuery.viewInsetsOf(context).bottom,
  ),
  child: const TextField(),
)

26. Detecting Device Pixel Ratio


Flutter exposes the device pixel ratio through MediaQuery.


final ratio =
    MediaQuery.of(context).devicePixelRatio;

print("Device Pixel Ratio: $ratio");


The device pixel ratio describes the relationship between physical pixels and logical pixels. For ordinary responsive layout calculations, logical pixels are generally the appropriate measurement. :contentReference[oaicite:15]{index=15}


27. Screen Size Categories


You can define application-specific categories for responsive behavior.


enum ScreenType {
  small,
  medium,
  large,
}

ScreenType getScreenType(BuildContext context) {
  final width = MediaQuery.widthOf(context);

  if (width < 600) {
    return ScreenType.small;
  }

  if (width < 1024) {
    return ScreenType.medium;
  }

  return ScreenType.large;
}


Usage:


final type = getScreenType(context);

switch (type) {
  case ScreenType.small:
    return const MobileLayout();
  case ScreenType.medium:
    return const TabletLayout();
  case ScreenType.large:
    return const DesktopLayout();
}


28. Complete Responsive Screen Detection Example


import 'package:flutter/material.dart';

class ResponsiveScreen extends StatelessWidget {
  const ResponsiveScreen({super.key});

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.sizeOf(context);
    final width = size.width;
    final height = size.height;

    if (width < 600) {
      return _buildSmallScreen(width, height);
    }

    if (width < 1024) {
      return _buildMediumScreen(width, height);
    }

    return _buildLargeScreen(width, height);
  }

  Widget _buildSmallScreen(double width, double height) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Small Screen"),
      ),
      body: Center(
        child: Text(
          "Width: $width\nHeight: $height",
          textAlign: TextAlign.center,
        ),
      ),
    );
  }

  Widget _buildMediumScreen(double width, double height) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Medium Screen"),
      ),
      body: Row(
        children: [
          const SizedBox(
            width: 220,
            child: ColoredBox(
              color: Colors.blueGrey,
              child: Center(
                child: Text(
                  "Sidebar",
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
          ),
          Expanded(
            child: Center(
              child: Text(
                "Width: $width\nHeight: $height",
                textAlign: TextAlign.center,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildLargeScreen(double width, double height) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Large Screen"),
      ),
      body: Row(
        children: [
          const SizedBox(
            width: 280,
            child: ColoredBox(
              color: Colors.blueGrey,
              child: Center(
                child: Text(
                  "Large Sidebar",
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
          ),
          Expanded(
            child: Center(
              child: SizedBox(
                width: 800,
                child: Text(
                  "Width: $width\nHeight: $height",
                  textAlign: TextAlign.center,
                  style: const TextStyle(fontSize: 22),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}


29. Detecting Screen Size in a Dashboard


class Dashboard extends StatelessWidget {
  const Dashboard({super.key});

  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.widthOf(context);

    final columns = width < 600
        ? 1
        : width < 1000
            ? 2
            : 4;

    return Scaffold(
      appBar: AppBar(
        title: const Text("Dashboard"),
      ),
      body: GridView.count(
        padding: const EdgeInsets.all(16),
        crossAxisCount: columns,
        crossAxisSpacing: 16,
        mainAxisSpacing: 16,
        children: const [
          DashboardCard(
            title: "Users",
            value: "1,250",
          ),
          DashboardCard(
            title: "Orders",
            value: "540",
          ),
          DashboardCard(
            title: "Revenue",
            value: "₹85,000",
          ),
          DashboardCard(
            title: "Pending",
            value: "32",
          ),
        ],
      ),
    );
  }
}

class DashboardCard extends StatelessWidget {
  final String title;
  final String value;

  const DashboardCard({
    super.key,
    required this.title,
    required this.value,
  });

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(title),
            const SizedBox(height: 8),
            Text(
              value,
              style: const TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
      ),
    );
  }
}


30. Detecting Screen Size for Images


You can use the available width to control an image's display size.


Widget build(BuildContext context) {
  final width = MediaQuery.widthOf(context);

  final imageWidth = width < 600
      ? width * 0.9
      : 500.0;

  return Center(
    child: Image.network(
      "https://example.com/image.jpg",
      width: imageWidth,
      fit: BoxFit.cover,
    ),
  );
}


For production applications, also consider the image's aspect ratio and maximum dimensions so that it remains visually appropriate on very large windows.


31. Detecting Screen Size for Forms


Large screens can benefit from constrained form widths.


Widget build(BuildContext context) {
  final width = MediaQuery.widthOf(context);

  final formWidth =
      width < 600 ? width * 0.9 : 450.0;

  return Center(
    child: SizedBox(
      width: formWidth,
      child: Column(
        children: const [
          TextField(
            decoration: InputDecoration(
              labelText: "Email",
            ),
          ),
          SizedBox(height: 16),
          TextField(
            obscureText: true,
            decoration: InputDecoration(
              labelText: "Password",
            ),
          ),
        ],
      ),
    ),
  );
}


32. Detecting Screen Size for Login UI


Widget build(BuildContext context) {
  final width = MediaQuery.widthOf(context);

  final horizontalPadding =
      width < 600 ? 20.0 : 80.0;

  return Scaffold(
    body: SafeArea(
      child: SingleChildScrollView(
        padding: EdgeInsets.symmetric(
          horizontal: horizontalPadding,
          vertical: 30,
        ),
        child: Center(
          child: ConstrainedBox(
            constraints: const BoxConstraints(
              maxWidth: 450,
            ),
            child: Column(
              children: const [
                Text(
                  "Login",
                  style: TextStyle(
                    fontSize: 32,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(height: 30),
                TextField(
                  decoration: InputDecoration(
                    labelText: "Email",
                  ),
                ),
                SizedBox(height: 16),
                TextField(
                  obscureText: true,
                  decoration: InputDecoration(
                    labelText: "Password",
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    ),
  );
}


33. Avoid Checking "Phone" or "Tablet"


A common mistake is writing code like:


if (isTablet) {
  // Tablet UI
} else {
  // Phone UI
}

This is not a reliable basis for responsive layout because a tablet can run an application in a narrow split-screen window, while a desktop or large device can display a relatively small application window.


A better approach is:


final width = MediaQuery.widthOf(context);

if (width < 600) {
  // Compact layout
} else {
  // Wider layout
}


Flutter's adaptive-design guidance specifically recommends using available window size instead of hardware-type checks. :contentReference[oaicite:16]{index=16}


34. Avoid Hardcoded Screen Dimensions


Avoid designing an application around one fixed screen size.


For example, this can be problematic:


Container(
  width: 400,
  height: 800,
)

Instead, use flexible layouts and available constraints:


SizedBox(
  width: MediaQuery.widthOf(context) * 0.9,
  child: const Text("Responsive Content"),
)

Even better, combine flexible sizing with maximum constraints when appropriate:


Center(
  child: ConstrainedBox(
    constraints: const BoxConstraints(
      maxWidth: 700,
    ),
    child: const Text("Responsive Content"),
  ),
)

35. Screen Size Changes and Rebuilding


When the application window changes size, widgets that depend on MediaQuery.sizeOf(context) are rebuilt when the size changes.


This is useful for responsive interfaces because resizing a desktop window or browser window can automatically trigger a new layout calculation. :contentReference[oaicite:17]{index=17}


final width = MediaQuery.widthOf(context);

return Text(
  "Current width: $width",
);


Do not unnecessarily cache the returned size for later use because doing so can prevent the UI from responding correctly to size changes. :contentReference[oaicite:18]{index=18}


36. Testing Different Screen Sizes


After implementing screen-size detection, test your application at multiple dimensions.



  • Small phone width

  • Large phone width

  • Tablet width

  • Desktop width

  • Very wide desktop window

  • Short-height window

  • Landscape window

  • Portrait window

  • Resizable browser window

  • Split-screen or multi-window environments


On Flutter web, you can resize the browser window and observe responsive layout changes. Flutter's adaptive tutorial demonstrates this approach when testing different window sizes. :contentReference[oaicite:19]{index=19}


37. Testing Example


class ScreenTest extends StatelessWidget {
  const ScreenTest({super.key});

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.sizeOf(context);

    return Scaffold(
      body: Center(
        child: Container(
          padding: const EdgeInsets.all(20),
          child: Text(
            "Width: ${size.width}\n"
            "Height: ${size.height}",
            textAlign: TextAlign.center,
            style: const TextStyle(
              fontSize: 24,
            ),
          ),
        ),
      ),
    );
  }
}


38. Common Mistakes


Mistake 1: Using the Physical Screen Size for Normal UI


For ordinary responsive layouts, use the application window size rather than the physical display size.


Mistake 2: Using Device Type as the Breakpoint


Do not assume that every tablet provides a large application window or that every phone provides a narrow one.


Mistake 3: Using Orientation as the Main Responsive Rule


Orientation alone does not tell you the exact amount of space available to the application.


Mistake 4: Ignoring Local Constraints


If a widget is inside a small container, using the entire application-window width may result in incorrect layout decisions. Use LayoutBuilder when local constraints are what matter.


Mistake 5: No Maximum Width on Large Screens


Content can become excessively wide on desktop and web if every component stretches indefinitely.


Mistake 6: Ignoring Safe Areas


Content can overlap notches or system UI if safe areas are not considered.


39. Best Practices



  • Use MediaQuery.sizeOf(context) to obtain application-window size.

  • Use MediaQuery.widthOf(context) when only width is required.

  • Use MediaQuery.heightOf(context) when only height is required.

  • Prefer specific MediaQuery APIs over MediaQuery.of(context) when possible.

  • Base breakpoints on available space rather than device names.

  • Use LayoutBuilder for local component constraints.

  • Use flexible widgets such as Expanded, Flexible, and Wrap.

  • Use ConstrainedBox or similar constraints to limit excessive widths.

  • Use SafeArea where content needs protection from system UI.

  • Test desktop and web layouts using resizable windows.

  • Do not unnecessarily lock the application to a single orientation.

  • Design for different window sizes instead of specific hardware models.


These practices are consistent with Flutter's current adaptive-layout guidance. :contentReference[oaicite:20]{index=20}


40. Quick Reference













CodePurpose
MediaQuery.sizeOf(context)Get the current application-window size
MediaQuery.widthOf(context)Get the current application-window width
MediaQuery.heightOf(context)Get the current application-window height
MediaQuery.orientationOf(context)Get current orientation
MediaQuery.paddingOf(context)Get system/display safe-area padding
MediaQuery.viewInsetsOf(context)Get completely obscured areas such as keyboard space
LayoutBuilderGet local parent constraints
ConstrainedBoxApply minimum or maximum constraints
SafeAreaProtect content from system UI and display cutouts

41. Practice Exercises



  1. Create an application that displays its current width and height.

  2. Create a layout that displays one column below 600 logical pixels and two columns above 600 logical pixels.

  3. Create a responsive dashboard with 1, 2, and 4 columns depending on available width.

  4. Create a responsive login form with a maximum width of 450 logical pixels.

  5. Create a page that displays a sidebar on large windows and a compact layout on small windows.

  6. Use LayoutBuilder to make a reusable card responsive to its own container width.

  7. Create a responsive image gallery whose column count changes according to window width.

  8. Resize a Flutter web browser window and verify that the UI responds correctly.

  9. Create a page that uses SafeArea and displays MediaQuery padding values.

  10. Create a responsive navigation interface using NavigationBar on small windows and NavigationRail on larger windows.


42. Key Takeaways



  • Flutter uses logical pixels for normal layout measurements.

  • MediaQuery.sizeOf(context) provides the current application-window dimensions.

  • MediaQuery.widthOf(context) provides the current window width.

  • MediaQuery.heightOf(context) provides the current window height.

  • The application-window size is usually more useful for responsive UI than the physical device size.

  • LayoutBuilder should be used when the local parent constraints are more relevant than the complete application-window size.

  • Responsive breakpoints should be based on available space rather than device categories.

  • Large screens often benefit from maximum content widths.

  • SafeArea helps protect content from system UI and display cutouts.

  • Responsive layouts should be tested across many window sizes.


43. Official Flutter Resources



44. Flutter Course Resources


For structured Flutter training and practical learning, explore these resources:



Conclusion


Detecting screen size and dimensions is fundamental to responsive Flutter development. By using MediaQuery.sizeOf(), MediaQuery.widthOf(), and MediaQuery.heightOf(), developers can determine the space currently available to the Flutter application and adjust layouts accordingly. For component-level responsiveness, LayoutBuilder provides the local constraints supplied by the parent. Combining these tools with flexible widgets, meaningful breakpoints, maximum-width constraints, and SafeArea makes it possible to build Flutter applications that adapt to phones, tablets, desktops, web windows, and other screen configurations. :contentReference[oaicite:21]{index=21}


whatsapp